# -*- coding:utf-8 -*-
# File Name:resource_task.py
# Author:jing
# Date:2018/12/18
from kubernetes import client
from ygframe.logger import logger
from ygframe.task.cyclic_task import cyclic_task

from model.mongo_model.resource_info import ResourceInfo, Status
from util.kube_util.kube_op import get_ip
from util.resource_info_util import get_resource

__author__ = 'jing'


@cyclic_task(1)
def check_resource():
    for ri in ResourceInfo.query().filter(
            ResourceInfo.status == Status.RECEIVED).get():  # type:ResourceInfo
        logger.info('start processing create {}'.format(ri.resource_id))
        resource = get_resource(ri)
        resource.start()

        host_ip = get_ip(client.CoreV1Api(), ri)
        logger.info('updating {} ip:{}'.format(ri.resource_id, host_ip))
        ResourceInfo.query().filter(
            ResourceInfo.resource_id == ri.resource_id
        ).first().update(
            ResourceInfo.create_update_builder().set(
                host_ip=host_ip,
                status=Status.RUNNING
            ).get()
        )
        logger.info('create {} done'.format(ri.resource_id))
